module RailsMagick

  #ImageMagick Commands
  IDENTIFY = "identify"
  CONVERT = "convert"

  # Returns type, width and height of an image file
  # Throws IO Error if the file doesn't exist
  # Throws ImageError if the image can't be read
  def self.identify(file)

    #If the file doesn't exist, raise an IO Error
    if !File.exist?(file)
      raise IOError, "No such file #{file}"
    end

    #Returns the identify string
    result = `#{IDENTIFY} #{file}`

    if !$?.success?
      return false  #File is not an image. 
    end

    data = result.split(' ')
    dimensions = data[2].split('x')

    {
      type: data[1],
      width: dimensions[0].to_i,
      height: dimensions[1].to_i
    }
    
  end

  # Resamples an image. Preserves aspect ratio. 
  # width and height determine the bounding box
  def self.resample(infile, outfile, width, height, quality = 80)

    #If the file doesn't exist, raise an IO Error
    if !File.exist?(infile)
      raise IOError, "No such file #{file}"
    end

    #Do the convert
    result = `#{CONVERT} #{infile} -resize '#{width}x#{height}>' -quality #{quality} #{outfile}`

    if !$?.success?
      raise RuntimeError, "Couldn't resample image #{infile} to #{outfile}"
    end

    true

  end

  # Generates a thumbnail. Ruthless about cropping. 
  # regenerate_thumb - if false, will check the dimensions of the incoming thumbnail and NOT regenerate the thumbnail if it is the same size. Defaults to true so that it will ruthlessly crop and overwrite the thumbnail.
  def self.create_thumbnail(infile, outfile, width, height, quality = 80, regenerate_thumb = true)
    if !File.exist?(infile)
      raise IOError, "No such file #{file}"
    end

    # Check if the thumbnail is already the same width and height. Don't run if it is.
    if !regenerate_thumb
      info = self.identify(infile)
      if info[:width] == width and info[:height] == height
        # Copy the file
        FileUtils.copy(infile, outfile)
        return true
      end
    end

    # Do the convert
    result = `#{CONVERT} #{infile} -resize '#{width}x#{height}^' -quality #{quality} -gravity center -extent '#{width}x#{height}' #{outfile}`

    if !$?.success?
      raise RuntimeError, "Couldn't create thumbnail from #{infile} to #{outfile}"
    end

    true

  end

end
